﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using EyesBaby;
using System.Windows.Forms;

namespace EyesBabyAutoUpdate
{
    public partial class AutoUpdateService : ServiceBase
    {
        static string connectString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Application.StartupPath +"\\"+ System.Configuration.ConfigurationSettings.AppSettings["logDatabasePath"];
        LogHelper.BLL.Log bllLog = new LogHelper.BLL.Log(connectString);

        public AutoUpdateService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Timers.Timer timerUpdate = new System.Timers.Timer();
            timerUpdate.Interval = int.Parse(System.Configuration.ConfigurationSettings.AppSettings["intervalMillisecond"]);// *60;// 每隔一小时访问一次服务器
            timerUpdate.Elapsed += new System.Timers.ElapsedEventHandler(timerUpdate_Elapsed);
            timerUpdate.Enabled = true;
            timerUpdate.Start();

            LogHelper.Model.Log modLog = new LogHelper.Model.Log();
            modLog.Title = "服务操作";
            modLog.Content = "On Start";
            modLog.CreateDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            bllLog.Add(modLog);
        }

        void timerUpdate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                // 调用更新
                CallUpdate();
            }
            catch (Exception ex)
            {
                LogHelper.Model.Log modLog = new LogHelper.Model.Log();
                modLog.Title = "操作更新失败";
                modLog.Content = ex.Message + "---------------" + ex.Source;
                modLog.CreateDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                bllLog.Add(modLog);
            }
        }


        /// <summary>
        /// 调用更新
        /// </summary>
        private void CallUpdate()
        {
            LogHelper.Model.Log modLog = new LogHelper.Model.Log();

            // 判断是否有新版本
            AutoUpdate autoUpdate = new AutoUpdate();
            CurrentVesionHelper currentVesion = new CurrentVesionHelper();

            string updatexmlpath = System.Configuration.ConfigurationSettings.AppSettings["updateXmlPath"];
            UpdateXmlHelper updateXml = new UpdateXmlHelper(updatexmlpath);
            string oldVesion = currentVesion.CurrentVesion;
            string newVesion = updateXml.Vesion;
            string newDownURL = updateXml.DownURL;
            bool b = autoUpdate.IsNewVesion(newVesion, oldVesion);
            if (b)
            {
                string filename = newDownURL.Substring(newDownURL.LastIndexOf('/') + 1);
                string savePath = Application.StartupPath + "/update/" + filename;
                if (autoUpdate.DownNewEdition(newDownURL, savePath))
                {
                    string error = string.Empty;
                    string zipfilepath = savePath;
                    string unzipdir = Application.StartupPath + "\\update\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                    // 解压文件包
                    clsZip zip = new clsZip();
                    zip.UnZipFile(zipfilepath, unzipdir, out error);
                    string installDir = currentVesion.InstallDir = Application.StartupPath;
                    string programName = currentVesion.ProgramName;
                    // 关闭程序
                    System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(programName);
                    foreach (System.Diagnostics.Process p in ps)
                    {
                        p.Kill();
                    }
                    #region 覆盖原安装程序

                    System.Threading.Thread.Sleep(1000);
                    string installPath = installDir + "\\" + programName;
                    if (System.IO.Directory.Exists(installPath))
                    {
                        // 先删除原安装路径
                        System.IO.Directory.Delete(installPath, true);
                    }
                    // 再将新版本复制到原安装目录
                    CopyFolder copy = new CopyFolder();
                    copy.CopyDirectory(unzipdir, installDir);
                    //System.IO.Directory.Move(unzipdir, installDir);

                    #endregion
                    string exepath = "EyesBaby.exe";
                    string startpath = installPath + "\\" + exepath;
                    // 重启程序
                    System.Diagnostics.Process.Start(startpath);
                    // 记录新版本到CurrentInfo.config
                    currentVesion.CurrentVesion = newVesion;
                    currentVesion.UpdateDate = DateTime.Now.ToShortDateString();
                    currentVesion.UpdateVesion();
                    modLog.Content = "更新成功--新版本号:" + newVesion;
                }
                else
                    modLog.Content = "下载最新版本失败";
            }
            else
                modLog.Content = "没有发现新版本";
            modLog.Title = "调用更新服务";
            modLog.CreateDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            bllLog.Add(modLog);
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            LogHelper.Model.Log modLog = new LogHelper.Model.Log();
            modLog.Title = "服务操作";
            modLog.Content = "On Stop";
            modLog.CreateDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            bllLog.Add(modLog);
        }
    }
}
